package com.ctg.payroll2.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ctg.payroll2.bean.po.SysFunction;

@SuppressWarnings("unchecked")
public class MenuRecursion {
	private StringBuffer returnStr = new StringBuffer();

	private void recursionFn(List<SysFunction> list, SysFunction node) {
		if (hasChild(list, node)) {
			returnStr.append("{id:'");
			returnStr.append(node.getFunctionId()).append("'");
			returnStr.append(",text:'");
			returnStr.append(node.getFunctionName()).append("'");
			returnStr.append(",children:[");
			List childList = getChildList(list, node);
			Iterator it = childList.iterator();
			while (it.hasNext()) {
				SysFunction n = (SysFunction) it.next();
				recursionFn(list, n);
			}
			returnStr.append("]},");
		} else {
			returnStr.append("{id:'");
			returnStr.append(node.getFunctionId()).append("'");
			returnStr.append(",text:'");
			returnStr.append(node.getFunctionName()).append("'");
			returnStr.append(",action:'");
			returnStr.append(node.getLinkAddress()).append("'");
			returnStr.append(",leaf:true},");
			
		}
		
	}

	private boolean hasChild(List<SysFunction> list, SysFunction node) { // 判断是否有子节点
		return getChildList(list, node).size() > 0 ? true : false;
	}

	private List<SysFunction> getChildList(List<SysFunction> list,
			SysFunction node) { // 得到子节点列表
		List<SysFunction> li = new ArrayList<SysFunction>();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			SysFunction n = (SysFunction) it.next();
			if (n.getParentId().equals(node.getFunctionId())) {
				li.add(n);
			}
		}
		return li;
	}

	private String modifyStr(String returnStr) {// 修饰一下才能满足Extjs的Json格式
		return ("[" + returnStr + "]").replaceAll(",]", "]");

	}

	public static String getString(List<SysFunction> nodeList) {
		MenuRecursion r = new MenuRecursion();
		r.recursionFn(nodeList, nodeList.get(0));

		return r.modifyStr(r.getReturnStr());
	}

	public String getReturnStr() {
		return returnStr.toString();
	}

}
